﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace JustMoveIt.Logic
{
    class FolderHelper
    {
        private Dictionary<string, string> _extHash;
        public FolderHelper()
        {
            _extHash = new Dictionary<string, string>();
        }

        public void InitExtension(string fileName)
        {
            FileInfo info = new FileInfo(fileName);
            if (!info.Exists)
            {
                info.Create();
                return;
            }
            TextReader reader = new StreamReader(fileName);
            string line = reader.ReadLine();
            while (line != null)
            {
                if (!line.StartsWith("?"))//ignore line that starts with ? , those are comments
                {
                    ConvertLine(line);
                }
                
                line = reader.ReadLine();
            }
            try
            {
                reader.Close();
            }
            catch (Exception)
            {
            }
        }

        private void ConvertLine(string line)
        {
            string[] split = line.Split(new[] { '|' }, 2);
            if (_extHash.ContainsKey(split[1]))
            {
                return;
            }
            _extHash.Add(split[1].ToLower(), split[0]);
        }

        public string Convert(string extension , string destination)
        {
            extension = extension.ToLower();

            string folderName;
            _extHash.TryGetValue(extension, out folderName);
            if (folderName == null)
            {
                return null;
            }
            string[] split = folderName.Split(new[] { '*' }, 2);
            if (split[0] == "ABS") //Absolute Path
            {
                return split[1];
            }
            else if(split[0] == "REL")
            {
                return Path.Combine(destination, split[1]);
            }
            return null;

        }

    }
}
